React Context
#React
https://ja.reactjs.org/docs/context.html
コンテクストをいつ使用すべきか
コンテキストは、あるReactコンポーネントのツリーに対して「グローバル」とみなすことができるデータを共有するためのもの。例えば以下のようなもの。
認証済みユーザー
テーマ
有線言語
(etc)
コンテキストで共有されたデータは props を経由することなく共有することができる。
試してみる
プロジェクトを作成。
code:sh
cd src
npm create vite@latest hello-app -- --template react-ts
cd hello-app
npm install
npm run dev
コンテキスト適用前のサンプルプログラム
コンテキスト適用前の、ヘッダとリスト要素を持つサンプルプログラム。
code:App.tsx
type HeaderProps = {
title: string
}
function Header(props: HeaderProps) {
const { title } = props;
return (
<h1>{title}</h1>
)
}
type ItemsProps = {
items: string[]
}
function Items({ items }: ItemsProps) {
return (
<ul>
{items.map((e) => <li key={e}>{e}</li>)}
</ul>
)
}
const items = "Apple", "Banana", "Orange"
function App() {
return (
<div>
<Header title="Hello" />
<Items items={items} />
</div>
)
}
export default App
こんな感じ。
https://gyazo.com/0d3396121c156266d7757a791ce72ea5
コンテキスト適用後
code:App.tsx
import React, { useContext } from "react";
// 1. コンテキストを作成
const ThemeContext = React.createContext("black")
type HeaderProps = {
title: string
}
function Header({ title }: HeaderProps) {
// 3. コンテキストから値を取得
const color = useContext(ThemeContext)
return (
<h1 style={{color: color}}>{title}</h1>
)
}
type ItemsProps = {
items: string[]
}
function Items({ items }: ItemsProps) {
// 3. コンテキストから値を取得
const color = useContext(ThemeContext)
return (
<ul>
{items.map((e) => <li key={e} style={{color: color}}>{e}</li>)}
</ul>
)
}
const items = "Apple", "Banana", "Orange"
function App() {
return (
// 2. コンテキストを適用したツリーをコンテキストのプロバイダで囲う
<ThemeContext.Provider value={"red"}>
<div>
<Header title="Hello" />
<Items items={items} />
</div>
</ThemeContext.Provider>
)
}
export default App
テーマの色を変えれる。
https://gyazo.com/f429ad1cfd7e4cea538e7a0703bc2ed4